package cloud.xlh.my_system.service.impl;

import cloud.xlh.my_system.common.response.Response;
import cloud.xlh.my_system.mapper.ProjectMapper;
import cloud.xlh.my_system.pojo.*;
import cloud.xlh.my_system.service.DatabaseService;
import cloud.xlh.my_system.service.ProjectService;
import cloud.xlh.my_system.utils.IdWorker;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.*;
import java.util.function.Consumer;


/**
 * Created with IntelliJ IDEA.
 *
 * @ project name : code-generator
 * @ Author: XuLeHuang
 * @ Date: 2022/6/1 12:50
 * @ Description:
 */
@Service
@Transactional
public class ProjectServiceImpl implements ProjectService {
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private DatabaseService databaseService;
    @Autowired
    private IdWorker idWorker;

    @Override
    public Response<HashMap> getListData(Integer limit, Integer page) {
        List<Project> projectList= projectMapper.findAllProjectToPage(limit , page - 1);
        //List<Long> dbIds = projectList.stream().map(Project::getDatabaseId).collect(Collectors.toList());
        List<ProjectRsp> projectRspsList = new ArrayList<>();
        projectList.stream().forEach(new Consumer<Project>() {
            @Override
            public void accept(Project project) {
                Long databaseId = project.getDatabaseId();
                Database database = databaseService.findDatabaseById(databaseId);
                ProjectRsp projectRsp = new ProjectRsp();
                BeanUtils.copyProperties(project, projectRsp);
                projectRsp.setDbName(database.getDbName());
                projectRspsList.add(projectRsp);
            }
        });
        HashMap<String, Object> map = new HashMap<>();
        map.put("rows" , projectRspsList);
        map.put("limit" , limit);
        map.put("total" , page);
        return Response.success(map);
    }

    @Override
    public boolean save(ProjectForm projectForm) {
        Project project = new Project();
        BeanUtils.copyProperties(projectForm, project);
        project.setId(idWorker.nextId() + "");
        project.setCreateDate(new Date());
        project.setUpdateDate(new Date());
        int rows = projectMapper.add(project);
        if (rows > 0) {
            return true;
        }
        return false;
    }

    @Override
    public Response<HashMap> option(PageRequest pageRequest) {
        return getListData((int) pageRequest.getLimit(), (int) pageRequest.getPage());
    }

    @Override
    public Project findProjectByProjectId(String projectId) {
        return projectMapper.findProjectByProjectId(projectId);
    }

}
